package cn.kgc.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

/**
 * @author: mosin
 * @version: v1.0  2023/1/7
 * shiro的认证流程  通过自定义realm完成认证操作
 */
public class TestAuthentication2 {

    public static void main(String[] args) {


        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        // 创建自定义realm实例对象
        CustomerRealm customerRealm = new CustomerRealm();
        // 创建凭证匹配器的实例对象 MD5
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher("MD5");
        // 设置md5加密的次数
        hashedCredentialsMatcher.setHashIterations(5);
        // 给域对象设置密码凭证匹配器 实现密码的验证
        customerRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        defaultSecurityManager.setRealm(customerRealm);
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("admin", "12345");


        subject.login(usernamePasswordToken);
        System.out.println("认证通过");

        //  授权操作   权限校验   1.编程式  2.注解式

        // 判定用户是否具有某个角色  admin
        //boolean b = subject.hasRole("super");
        // 判定用户是否同时拥有多个角色
        boolean b = subject.hasAllRoles(Arrays.asList("admin", "super"));
        System.out.println("b = " + b);
        // 用户是否拥有指定的角色
        boolean[] booleans = subject.hasRoles(Arrays.asList("customer", "super"));
        for (boolean aBoolean : booleans) {
            System.out.println("aBoolean = " + aBoolean);
        }

        //  通过权限字符串实现权限校验    user:add  user:update  user:list  user:delete
        boolean permitted = subject.isPermitted("user:add");
        System.out.println("permitted = " + permitted);



    }
}
